package com.bjsxt.livegoods.dao.product;

import com.bjsxt.livegoods.entity.Product;

import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.List;
@Component
public class ProductDaoImpl implements ProductDao{
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public List<Product> findProducts(Query query) {
        List<Product> products=this.mongoTemplate.find(query,Product.class);
        return products;
    }
    //主键查询商品
    @Override
    public Product findById(String id) {
        return mongoTemplate.findById(id,Product.class);
    }

    //新增商品
    @Override
    public void insertProduct(Product product) {
        this.mongoTemplate.insert(product);
    }
    //修改商品状态为1 已订购
    @Override
    public boolean updateProduct(Product product) {
        Query query=new Query();
        query.addCriteria(Criteria.where("_id").is(product.getId()));
        query.addCriteria(Criteria.where("status").is("2"));
        Update update=Update.update("status","1");
        UpdateResult result=mongoTemplate.updateFirst(query,update,Product.class);
        long modifiedCount = result.getModifiedCount();
        return modifiedCount==1L;
    }

    //在hotproductservice中设置mongoTemplate
    public void setMongoTemplate(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }

}
